package com.huashi.dealer.modular.business.discount.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huashi.dealer.commonEntity.DiscountActive;
import com.huashi.dealer.commonEntity.DiscountActiveGoods;
import com.huashi.dealer.commonEntity.DiscountActiveSpec;
import com.huashi.dealer.modular.business.discount.mapper.DiscountActiveGoodsMapper;
import com.huashi.dealer.modular.business.discount.mapper.DiscountActiveMapper;
import com.huashi.dealer.modular.business.discount.mapper.DiscountActiveSpecMapper;
import com.huashi.dealer.modular.business.discount.param.DiscountActiveListParam;
import com.huashi.dealer.modular.business.discount.param.DiscountActiveSaveParam;
import com.huashi.dealer.modular.business.discount.service.StoreDiscountActiveService;
import com.huashi.dealer.modular.business.discount.vo.DiscountActiveDetailsVo;
import com.huashi.dealer.modular.business.discount.vo.DiscountActiveGoodsVo;
import com.huashi.dealer.commonEntity.Goods;
import com.huashi.dealer.modular.business.goods.mapper.GoodsMapper;
import com.huashi.dealer.modular.business.goods.mapper.GoodsImageMapper;
import com.huashi.dealer.modular.business.goods.vo.GoodsImageWithUrl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class StoreDiscountActiveServiceImpl implements StoreDiscountActiveService {

    @Resource
    private DiscountActiveMapper discountActiveMapper;
    @Resource
    private DiscountActiveGoodsMapper discountActiveGoodsMapper;
    @Resource
    private DiscountActiveSpecMapper discountActiveSpecMapper;
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private GoodsImageMapper goodsImageMapper;

    @Override
    public Page<DiscountActive> getDiscountActiveList(DiscountActiveListParam param, Page<DiscountActive> page) {
        LambdaQueryWrapper<DiscountActive> qw = new LambdaQueryWrapper<>();
        qw.eq(DiscountActive::getIsDelete, 0);
        
        // 标题模糊查询
        if (StringUtils.hasText(param.getTitle())) {
            qw.like(DiscountActive::getTitle, param.getTitle());
        }
        
        // 状态筛选
        if (param.getStatus() != null) {
            qw.eq(DiscountActive::getStatus, param.getStatus());
        }
        
        qw.orderByDesc(DiscountActive::getDiscountId);
        return discountActiveMapper.selectPage(page, qw);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateDiscountActive(DiscountActiveSaveParam param) {
        DiscountActive entity = new DiscountActive();
        entity.setDiscountId(param.getDiscountId());
        entity.setTitle(param.getTitle());
        entity.setCreateTime(System.currentTimeMillis() / 1000);
        entity.setUpdateTime(System.currentTimeMillis() / 1000);
        Integer minNum = param.getSetNum().stream()
                .map(DiscountActiveSaveParam.SpecItem::getNum)
                .min(Integer::compareTo)
                .orElse(0);
        Integer minNum1 = param.getMinNum();
        entity.setSetNum(minNum > minNum1? minNum1 : minNum);
        
        // 设置状态：新增时使用传入值，编辑时保持原值
        if (param.getStatus() != null) {
            entity.setStatus(param.getStatus());
        } else if (entity.getDiscountId() == null) {
            // 新增时如果没有传入状态，默认启用
            entity.setStatus(10);
        }
        
        Long discountId;
        if (entity.getDiscountId() == null) {
            // 新增模式
            discountActiveMapper.insert(entity);
            discountId = entity.getDiscountId(); // 获取插入后的主键
        } else {
            // 编辑模式
            discountActiveMapper.updateById(entity);
            discountId = entity.getDiscountId();
            
            // 清空旧关联
            discountActiveGoodsMapper.delete(new LambdaQueryWrapper<DiscountActiveGoods>()
                    .eq(DiscountActiveGoods::getDiscountId, discountId));
            discountActiveSpecMapper.delete(new LambdaQueryWrapper<DiscountActiveSpec>()
                    .eq(DiscountActiveSpec::getDiscountId, discountId));
        }

        // 保存商品关联
        if (param.getGoodsIds() != null && !param.getGoodsIds().isEmpty()) {
            List<DiscountActiveGoods> goodsList = new ArrayList<>();
            for (Long goodsId : param.getGoodsIds()) {
                DiscountActiveGoods g = new DiscountActiveGoods();
                g.setDiscountId(discountId);
                g.setGoodsId(goodsId);
                g.setCreateTime(System.currentTimeMillis() / 1000);
                goodsList.add(g);
            }
            for (DiscountActiveGoods g : goodsList) {
                discountActiveGoodsMapper.insert(g);
            }
        }

        // 保存起订规格
        if (param.getSetNum() != null && !param.getSetNum().isEmpty()) {
            for (DiscountActiveSaveParam.SpecItem item : param.getSetNum()) {
                DiscountActiveSpec spec = new DiscountActiveSpec();
                spec.setDiscountId(discountId);
                spec.setNum(item.getNum());
                spec.setPrice(item.getPrice());
                spec.setCreateTime(System.currentTimeMillis() / 1000);
                discountActiveSpecMapper.insert(spec);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDiscountActive(Long discountId) {
        discountActiveMapper.deleteById(discountId);
    }

    @Override
    public void updateDiscountActiveStatus(Long discountId, Integer state) {
        DiscountActive entity = new DiscountActive();
        entity.setDiscountId(discountId);
//        entity.setStatus(state != null && state == 1 ? 10 : 20);
        entity.setStatus(state);
        discountActiveMapper.updateById(entity);
    }

    @Override
    public DiscountActiveDetailsVo getDiscountActiveDetails(Long discountId) {
        // 获取活动基本信息
        DiscountActive discountActive = discountActiveMapper.selectById(discountId);
        if (discountActive == null || discountActive.getIsDelete() == 1) {
            return null;
        }

        // 获取关联商品列表
        List<DiscountActiveGoods> activeGoodsList = discountActiveGoodsMapper.selectList(
                new LambdaQueryWrapper<DiscountActiveGoods>()
                        .eq(DiscountActiveGoods::getDiscountId, discountId)
        );

        // 构建商品VO列表（包含图片信息）
        List<DiscountActiveGoodsVo> goodsVoList = new ArrayList<>();
        for (DiscountActiveGoods activeGoods : activeGoodsList) {
            DiscountActiveGoodsVo goodsVo = new DiscountActiveGoodsVo();
            goodsVo.setGoodsId(activeGoods.getGoodsId());
            
            // 查询商品基本信息
            Goods goods = goodsMapper.selectById(activeGoods.getGoodsId());
            if (goods != null) {
                goodsVo.setGoodsName(goods.getGoodsName());
                goodsVo.setGoodsPrice(goods.getGoodsPrice());
                goodsVo.setGoodsStatus(goods.getGoodsStatus());
                
                // 查询商品图片（一次性获取图片ID和URL）
                List<GoodsImageWithUrl> imageInfos = goodsImageMapper.getGoodsImageWithUrl(activeGoods.getGoodsId());
                if (imageInfos != null && !imageInfos.isEmpty()) {
                    GoodsImageWithUrl firstImage = imageInfos.get(0);
                    goodsVo.setImageId(firstImage.getImageId()); // 设置图片ID
                    goodsVo.setImageUrl(firstImage.getFileUrl()); // 设置图片URL
                }
            }
            
            goodsVoList.add(goodsVo);
        }

        // 获取起订规格列表
        List<DiscountActiveSpec> specList = discountActiveSpecMapper.selectList(
                new LambdaQueryWrapper<DiscountActiveSpec>()
                        .eq(DiscountActiveSpec::getDiscountId, discountId)
                        .orderByAsc(DiscountActiveSpec::getNum)
        );

        DiscountActiveDetailsVo detailsVo = new DiscountActiveDetailsVo();
        detailsVo.setDiscountActive(discountActive);
        detailsVo.setGoodsList(goodsVoList);
        detailsVo.setSpecList(specList);

        return detailsVo;
    }
}


